package cn.piggy.config;

import cn.piggy.quartz.listener.MyJobListener;
import org.quartz.spi.JobFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class QuartzConfig {
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setJobFactory(jobFactory());

        factory.setStartupDelay(3);
        factory.setAutoStartup(true);
        factory.setOverwriteExistingJobs(true);
        factory.setDataSource(dataSource);
        factory.setQuartzProperties(quartzProperties());
//        factory.setTaskExecutor();

        factory.setGlobalJobListeners(new MyJobListener());
        return factory;
    }

    @Bean
    public JobFactory jobFactory() {
        return new SpringBeanJobFactory();
    }

    @Bean
    public Properties quartzProperties() {
        Properties props = new Properties();
        props.put("org.quartz.scheduler.instanceId", "AUTO");
        props.put("org.quartz.scheduler.instanceName", "globalScheduler");
        props.put("org.quartz.scheduler.batchTriggerAcquisitionMaxCount", "30");
//        props.put("org.quartz.scheduler.batchTriggerAcquisitionFireAheadTimeWindow", "30000");

        props.put("org.quartz.jobStore.misfireThreshold", "60000");
        props.put("org.quartz.jobStore.class", "org.springframework.scheduling.quartz.LocalDataSourceJobStore");
        props.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
        props.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
        props.put("org.quartz.jobStore.isClustered", "true");
        props.put("org.quartz.jobStore.acquireTriggersWithinLock", "true");
        props.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "10");
        props.put("org.quartz.jobStore.clusterCheckinInterval", "20000");

        props.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
        props.put("org.quartz.threadPool.threadCount", "20");
        props.put("org.quartz.threadPool.threadPriority", "5");
        props.put("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread", "false");
        props.put("org.quartz.threadPool.threadNamePrefix", "piggy_quartz");

        return props;
    }
}
